<script setup lang="ts">
import { ElCard, ElRow, ElCol, ElTabs, ElTabPane, ElAvatar, ElMessage } from 'element-plus'
import { computed, ref, unref } from 'vue'
import InfoWrite from './components/InfoWrite.vue'
import PasswordWrite from './components/PasswordWrite.vue'
import { useAuthStore } from '@/store/modules/auth'
import avatar from '@/assets/imgs/avatar.jpg'
import { selectDictLabel, DictDetail } from '@/utils/dict'
import { useDictStore } from '@/store/modules/dict'
import UploadAvatar from './components/UploadAvatar.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { postCurrentUserUpdateAvatar } from '@/api/vadmin/auth/user'

const activeName = ref('info')

const authStore = useAuthStore()

let genderOptions = ref<DictDetail[]>([])

const getOptions = async () => {
  const dictStore = useDictStore()
  const dictOptions = await dictStore.getDictObj(['sys_vadmin_gender'])
  genderOptions.value = dictOptions.sys_vadmin_gender
}

getOptions()

const user = computed(() => authStore.getUser)
// 将base64转换为File对象
// 将base64转换为File对象
const base64ToFile = (base64: string, filename: string = 'avatar.png'): File => {
  // 分离base64数据的MIME类型和实际数据
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/png'
  const bstr = atob(arr[1] || arr[0])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}

const postCurrentUserUpdate = async (data: any) => {
  try {
    const res = await postCurrentUserUpdateAvatar(data)
    if (res) {
      authStore.updateUser(res.data)
      user.value.avatar = res.data.avatar
      ElMessage.success('头像更新成功')
    }
  } catch (error) {
    console.error('更新用户头像失败:', error)
    ElMessage.error('头像更新失败')
    throw error
  }
}
const dialogVisible = ref(false)
const avatarLoading = ref(false)
const uploadAvatarRef = ref<ComponentRef<typeof UploadAvatar>>()
const saveAvatar = async () => {
  try {
    avatarLoading.value = true
    //
    const base64 = unref(uploadAvatarRef)?.getBase64() as string
    if (!base64) {
      ElMessage.warning('请先选择或上传头像')
      return
    }
    // 将base64转换为File对象
    const file = base64ToFile(base64)
    // 创建FormData并添加文件
    const formData = new FormData()
    formData.append('file', file)
    formData.append('path', 'avatar')
    // 这里可以调用修改头像接口
    // fetchDetailUserApi()
    await postCurrentUserUpdate(formData)
    // ElMessage.success('修改成功')
    dialogVisible.value = false
  } catch (error) {
    console.log(error)
  } finally {
    avatarLoading.value = false
  }
}
</script>

<template>
  <div class="p-20px">
    <ElRow :gutter="20">
      <ElCol :xs="24" :sm="12" :md="8">
        <ElCard shadow="hover" class="pb-30px">
          <div class="text-center" @click="dialogVisible = true">
            <ElAvatar :size="80" :src="user.avatar ? user.avatar : avatar" />
            <p style="font-size: 24px">{{ user.name }}</p>
          </div>
          <div class="pl-20px pt-30px">
            <div class="leading-relaxed">
              <span class="pl-10px w-80px inline-block">姓名:</span>
              <span class="pl-10px">{{ user.name }}</span>
            </div>
            <div class="leading-relaxed">
              <span class="pl-10px w-80px inline-block">昵称:</span>
              <span class="pl-10px">{{ user.nickname }}</span>
            </div>
            <div class="leading-relaxed">
              <span class="pl-10px w-80px inline-block">手机号:</span>
              <span class="pl-10px">{{ user.telephone }}</span>
            </div>
            <div class="leading-relaxed">
              <span class="pl-10px w-80px inline-block">性别:</span>
              <span class="pl-10px">{{
                selectDictLabel(genderOptions, user.gender as string)
              }}</span>
            </div>
            <div class="leading-relaxed">
              <span class="pl-10px w-80px inline-block">角色:</span>
              <span class="pl-10px">{{ user.roles?.map((item) => item.name).join(',') }}</span>
            </div>
            <div class="leading-relaxed">
              <span class="pl-10px w-80px inline-block">创建时间:</span>
              <span class="pl-10px">{{ user.create_datetime }}</span>
            </div>
          </div>
        </ElCard>
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="16">
        <ElCard shadow="hover">
          <ElTabs v-model="activeName">
            <ElTabPane label="基本信息" name="info">
              <InfoWrite />
            </ElTabPane>
            <ElTabPane label="修改密码" name="password">
              <PasswordWrite />
            </ElTabPane>
          </ElTabs>
        </ElCard>
      </ElCol>
    </ElRow>
  </div>
  <Dialog v-model="dialogVisible" title="修改头像" width="800px">
    <UploadAvatar ref="uploadAvatarRef" :url="user.avatar ? user.avatar : avatar" />

    <template #footer>
      <div class="action-buttons">
        <BaseButton :loading="avatarLoading" type="primary" @click="saveAvatar"> 保存 </BaseButton>
        <BaseButton @click="dialogVisible = false">取消</BaseButton>
      </div>
    </template>
  </Dialog>
</template>
